package template;

import com.qcloud.cos.COS;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingResponse;
import properties.CosProperties;

import java.io.File;
import java.io.InputStream;

public class CosTemplate {
    private COSClient cosClient = null;
    private CosProperties cosProperties = null;

    public CosTemplate(COSClient cosClient, CosProperties cosProperties) {
        this.cosClient = cosClient;
        this.cosProperties = cosProperties;
    }

    public String testUpload(InputStream file,String originalName) {
        try {
//        File localFile = new File("D:\\桌面\\test.png");
            // 指定文件将要存放的存储桶
//            String bucketName = "sxb-1323573758";
            // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
            String fileName = System.currentTimeMillis() + originalName;
            String key = cosProperties.getFolder() + "/" + fileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(), key, file,null);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            testImageAudit(key);
            //https://sxb-1323573758.cos.ap-chengdu.myqcloud.com/test%2Ftest.png
            return String.format(cosProperties.getFilePathTemplate(), cosProperties.getBucketName(), cosProperties.getRegionName(), cosProperties.getFolder(), fileName);
        } catch (CosClientException e) {
            throw new RuntimeException("文件上传失败");
        }
    }
    public void testImageAudit(String objectKey) {
        try {
            //1.创建任务请求对象
            ImageAuditingRequest request = new ImageAuditingRequest();
            //2.添加请求参数 参数详情请见 API 接口文档
            //2.1设置请求 bucket
            request.setBucketName(cosProperties.getBucketName());
            //2.2设置审核策略 不传则为默认策略（预设）
            //request.setBizType("");
            //2.3设置bucket中的图片位置
            request.setObjectKey(objectKey);
            //3.调用接口,获取任务响应对象
            ImageAuditingResponse response = cosClient.imageAuditing(request);
            if(!"0".equals(response.getResult())){
                throw new RuntimeException("图片审核失败");
            }
        } catch (CosClientException e) {
            throw new RuntimeException("文件上传失败");
        }
    }
}
